﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Interactivity;
using System.Text;
using RStein.PosterousReader.WP.Extensions;

namespace RStein.PosterousReader.WP.Behaviors
{
    public class WebBrowserNavigateBehavior : Behavior<WebBrowser>
    {

       
        public static string GetNavigateText(DependencyObject obj)
        {
          return (string) obj.GetValue(NavigateText);
        }

        public static void SetNavigateText(DependencyObject obj, string value)
        {
          obj.SetValue(NavigateText, value);
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty NavigateText =
            DependencyProperty.RegisterAttached("NavigateText", typeof(string), typeof(WebBrowserNavigateBehavior), new PropertyMetadata(String.Empty,
                                                                                                                                         NavigateTextChanged));

        
        protected static void NavigateTextChanged (DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
          
            var browser = d as WebBrowser;                      
            var htmlString = e.NewValue.ToString().HtmlDecode().EncodeUnicodeChars();
            try
            {
              if (browser != null)
              {

                browser.NavigateToString(htmlString);
                
              }
            }
            //Temporary fix for "browser not in visual tree issue"
            catch (InvalidOperationException ex)
            {
              RoutedEventHandler loadedHandler = null;

              loadedHandler = (_, __) =>
                              {
                                browser.NavigateToString(htmlString);
                                browser.Loaded -= loadedHandler;
                              };

              browser.Loaded += loadedHandler;
            }
          
        }



        
    }
}
